<template>
  <div>
    <el-dialog width="30%" :visible.sync="dialogVisible" title="修改密码" :before-close="handleDialogClose">
      <el-form label-width="100px" :model="dataForm" :rules="rules" ref="dataForm">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="dataForm.newPassword" style="width: 250px;margin-left: -50px"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="dataForm.confirmPassword" style="width: 250px;margin-left: -50px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: -80px" @click="updatePassword">提交</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "PasswordForm",
  data() {
    //自定义确认密码校验
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if (value !== this.dataForm.newPassword) {
        callback(new Error('密码不一致'));
      } else {
        callback();
      }
    };
    return {
      dataForm: {
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {validator: validatePassword, trigger: 'blur'}
        ]
      }
    }
  },
  props: {
    dialogVisible: Boolean
  },
  methods: {
    handleDialogClose() {
      this.dataForm = {
        newPassword: '',
        confirmPassword: ''
      }
      this.$emit('update:dialogVisible', false)
    },
    //关闭对话框
    closeDialog() {
      this.dataForm = {
        newPassword: '',
        confirmPassword: ''
      }
      this.$emit('update:dialogVisible', false)
    },
    //修改密码
    updatePassword() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          request.put('/user/client/updatePassword', this.dataForm).then(res => {
            if (res.data.code === 200) {
              this.closeDialog()
              this.$message.success({message: '恭喜你，修改成功', type: "success"})
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>